﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using Baimasoft.FrameWork.Base;
using Baimasoft.Manage.SqlServerDAL;
using HsTec.Mobile.Green.SqlServerDAL;

public partial class DocumentManage_Document_Lend : Baimasoft.Web.UI.PageManagerTop
{
    HsTec.Mobile.Green.SqlServerDAL.SendFile MySendFile = new HsTec.Mobile.Green.SqlServerDAL.SendFile();
    HsTec.Mobile.Green.SqlServerDAL.DataFolder MyDF = new HsTec.Mobile.Green.SqlServerDAL.DataFolder();

    BaimasoftFile MyFile = new BaimasoftFile();
    DataFile datafile = new DataFile();
    Machineroom machineroom = new Machineroom();
    Network MyNt = new Network();
    Area area = new Area();
    Project project = new Project();

    AspNetHelper MyAH = new AspNetHelper();

    public string sID = "-1";

    protected void Page_Load(object sender, EventArgs e)
    {
        this.BindControlEvent();
        this.HiddenID.Value = "";

        if (!this.IsPostBack)
        {
            if ((string)Session["Baimasoft_Pers_ID"] == null)
            {
                Response.Redirect("../logon.aspx");
            }

            try
            {
                AspNetHelper.IndexPageLoad(this, this.Indicator); //导航
                AspNetHelper.BtnGrantInfo(this);  //按钮控制   注意前后加载顺序: 先加载导航,后加载按钮控制; 页面加载顺序是从上向下加载的
            }
            catch
            {
            }
            ChoiceDt.Checked = true;
            ifChoiceDt.Style.Add("display", "");
            AllDt.Style.Add("display", "none");

            GridView1.Attributes.Add("BorderColor", "LightSkyBlue");
            this.SDT.Text = DateTime.Now.ToString("yyyy-MM") + "-01";
            this.EDT.Text = DateTime.Now.ToString("yyyy-MM-dd");
            ddlRegionDataBind();
            ddlMachineDataBind();
            ddlnetworkDataBind();
            ddlProjectDataBind();
            this.BindGridViewData();//绑定GridView,为删除服务            //string spageid = HttpContext.Current.Session[SessionConst.PageID].ToString ();
        }
    }

    protected override void BindGridViewData()
    {
        this.DataSource = datafile.GetDataFileInfos (GetSearchString());
        this.DataSource.DefaultView.Sort = this.SortString;
        GridView1.DataSource = this.DataSource.DefaultView;
        GridView1.DataBind();
        KeepStyle();
    }

    /// <summary>
    /// 区域下拉框
    /// </summary>
    protected void ddlRegionDataBind()
    {
        ddlRegionid.DataSource = area.GetAreaInfos(string.Empty);
        ddlRegionid.DataBind();
        ddlRegionid.Items.Insert(0, "全部");
        ddlRegionid.Items[0].Value = "0";
    }

    /// <summary>
    /// 机房下拉框绑定
    /// </summary>
    protected void ddlMachineDataBind()
    {
        ddlMachineid.DataSource = machineroom.GetMachineRooms("");
        ddlMachineid.DataBind();
        ddlMachineid.Items.Insert(0, "全部");
        ddlMachineid.Items[0].Value = "0";
    }

    /// <summary>
    /// 网元下拉框绑定
    /// </summary>
    protected void ddlnetworkDataBind()
    {
        ddlnetwork.DataSource = MyNt.GetNetWorks ("");
        ddlnetwork.DataBind();
        ddlnetwork.Items.Insert(0, "全部");
        ddlnetwork.Items[0].Value = "0";
    }

    /// <summary>
    /// 项目下拉框
    /// </summary>
    protected void ddlProjectDataBind()
    {
        this.ddlProject.DataSource = project.GetProjectInfos ("");
        this.ddlProject.DataBind();
        this.ddlProject.Items.Insert(0, "全部");
        this.ddlProject.Items[0].Value = "0";
    }

    protected override string GetSearchString()
    {
        string searchStr = string.Empty;
        searchStr += " ( 1=1) ";

        if (ChoiceName_1.Value.ToString().Trim() != "")
        {
            if (HChoiceID_1.Value.ToString().Trim() != "")
            {
                searchStr += " and a.FolderID in(" + HChoiceID_1.Value.ToString().Trim() + ") ";
            }
        }

        if (this.Name.Text.Trim().Length > 0)
        {
            searchStr += " and a.Name like '%" + this.Name.Text.ToString().Trim() + "%' ";
        }

        if (this.KeyWord.Text.Trim().Length > 0)
        {
            searchStr += " and a.KeyWord like '%" + this.KeyWord.ToString().Trim() + "%' ";
        }

        if (ChoiceDt.Checked == true)
        {
            if (this.SDT.Text.ToString().Trim() != "")
            {
                searchStr += " and convert(varchar(10),a.CreatDT,120) >= '" + this.SDT.Text.ToString().Trim() + "' ";
            }
            else
            {
                searchStr += " and convert(varchar(10),a.CreatDT,120) >= '" + DateTime.Now.ToString("yyyy-MM-dd") + "' ";
            }
            if (this.EDT.Text.ToString().Trim() != "")
            {
                searchStr += " and convert(varchar(10),a.CreatDT,120) <= '" + this.EDT.Text.ToString().Trim() + "' ";
            }
            else
            {
                searchStr += " and convert(varchar(10),a.CreatDT,120) <= '" + DateTime.Now.ToString("yyyy-MM-dd") + "' ";
            }
        }

        string sddlRegionid = ddlRegionid.SelectedValue.ToString().Trim();
        if (sddlRegionid != "0")
        {
            searchStr += " and a.Region ='" + sddlRegionid + "' ";
        }
        if (ddlMachineid.SelectedValue.ToString().Trim() != "0")
        {
            searchStr += " and a.MachineRoom ='" + ddlMachineid.SelectedValue.ToString().Trim() + "' ";
        }
        if (ddlnetwork.SelectedValue.ToString().Trim() != "0")
        {
            searchStr += " and a.NetWork ='" + ddlnetwork.SelectedValue.ToString().Trim() + "' ";
        }
        if (ddlProject.SelectedValue.ToString().Trim() != "0")
        {
            searchStr += " and a.Project ='" + ddlProject.SelectedValue.ToString().Trim() + "' ";
        }

        #region 取该用户数据角色授权信息
        string sChoiceFolderCol = AspNetHelper.GetRightFolderIDCol();
        string sChoiceFileCol = AspNetHelper.GetRightFileIDCol();

        if ((sChoiceFolderCol.Trim() == "0" || sChoiceFolderCol.Length == 0) && (sChoiceFileCol.Trim() == "0" || sChoiceFileCol.Length == 0))
        { //没有授权的情况下
            //searchStr += " and  ( 1<>1 )";
        }
        else
        {

            if (sChoiceFolderCol.Trim() != "0" && sChoiceFolderCol.Length > 0)
            {
                string sFolderIDCols = MyDF.GetFolderChildIDCols(sChoiceFolderCol.Trim());
                if (sFolderIDCols != "")
                {
                    searchStr += " and a.FolderID in(" + sFolderIDCols + ") ";
                }
            }

            if (sChoiceFileCol.Trim() != "0" && sChoiceFileCol.Length > 0)
            {
                //自己的文档自己可以查看
                string sLogonID = Session["Baimasoft_User_LogonID"].ToString();
                if (sLogonID == "")
                {
                    sLogonID = "0";
                }

                if (sLogonID.ToUpper() != "ADMIN")
                {
                    searchStr += "  and (a.ID in(" + sChoiceFileCol + ") or a.creatrole = '" + sLogonID + "' )  ";
                }
                else
                {
                    searchStr += " and a.ID in(" + sChoiceFileCol + ") ";
                }
                //
            }
        }

        #endregion

        #region 取该用户借阅授权
        try
        {
            int iPersID = int.Parse((string)Session["Baimasoft_Pers_ID"]);
            int iback = MySendFile.GetFileSends(" SendTo in(" + iPersID + ") ").Rows.Count;
            if (iback > 0)
            {
                searchStr += " or a.ID in(SELECT FileID FROM FileSend WHERE (SendTo in(" + iPersID + ") )) ";
            }
        }
        catch
        {
        }

        #endregion

        searchStr += " order by a.name, versionnumber desc ";


        return searchStr;
    }

    protected void BtnRefresh1_Click(object sender, EventArgs e)
    {
        this.DataSource = datafile.GetDataFileInfos (GetSearchString());
        this.DataSource.DefaultView.Sort = this.SortString;
        GridView1.DataSource = this.DataSource.DefaultView;
        GridView1.DataBind();
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "Down")
            {
                string FileName,FileSwitchPath, FilePath, InFile;

                int index = Convert.ToInt32(e.CommandArgument);

                GridViewRow selectedRow = GridView1.Rows[index];

                TableCell TrueFileName = selectedRow.Cells[2];  //Name
                string sTrueFileName = TrueFileName.Text;

                TableCell contactName = selectedRow.Cells[3];  //AliasName
                FileName = contactName.Text;

                TableCell TSwitchPath = selectedRow.Cells[4];
                FileSwitchPath = TSwitchPath.Text;

                string m_Root = ConfigurationManager.AppSettings["DocumentMange"];  //取Web.Config文件中的配置信息,在配置的时候要注意该盘权限
                FilePath = m_Root + FileSwitchPath + "\\" + FileName;              //写到服务器上的路径

                //ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + str + "');</script>");
                InFile = FilePath;
                //--------------------------
                int Index;
                Index = FilePath.Trim().Length - FileName.Length;
                string OutFile;
                OutFile = FilePath.Remove(Index, FileName.Length);

                OutFile += "!" + FileName;
                string sEncryptFile = ConfigurationManager.AppSettings["EncryptFile"];

                MyFile.DecryptFile(InFile, OutFile, sEncryptFile); //对文件进行加密处理

                Response.Clear();
                Response.ClearHeaders();
                Response.Charset = "utf-8";
                Response.Buffer = false;
                this.EnableViewState = false;
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(sTrueFileName)));
                Response.WriteFile(OutFile);
                Response.Flush();
                Response.Close();

                MyFile.DeleteFile(OutFile);//删除临时文件

                Response.End();
            }
        }
        catch
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('文件下载失败！请与系统管理人员联系！');</script>");
            return;
        }
    }

    protected new void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex != -1)
        {
            HtmlInputCheckBox Chk = (HtmlInputCheckBox)(e.Row.Cells[0].FindControl("OneCheck"));
            if (ChoiceInfo.Value.IndexOf(e.Row.Cells[1].Text.Trim()) >= 0)
            {
                HtmlInputCheckBox ChkSelected = (HtmlInputCheckBox)(e.Row.Cells[0].FindControl("OneCheck"));
                ChkSelected.Checked = true;
            }

            if (e.Row.RowIndex % 2 != 0)
            {
                e.Row.Attributes.Add("onclick", "tog(this,'#EFEFF8')");
            }
            else
            {
                e.Row.Attributes.Add("onclick", "tog(this,'#F9F9FB')");
            }
        }
    }

    protected void ddlRegionid_SelectedIndexChanged(object sender, EventArgs e)
    {
        string sddlRegion = ddlRegionid.SelectedValue.ToString().Trim();

        DataTable dt1 = machineroom.GetMachineRooms ("a.region_id='" + sddlRegion + "'");
        this.ddlMachineid.DataValueField = "mroom_id";
        this.ddlMachineid.DataTextField = "mroom_name";
        this.ddlMachineid.DataSource = dt1;
        this.ddlMachineid.DataBind();

        string sddlMachine = ddlMachineid.SelectedValue.ToString().Trim();
        DataTable dt2 = MyNt.GetNetWorks ("a.mroom_id = '" + sddlMachine + "'");
        this.ddlnetwork.DataValueField = "netw_id";
        this.ddlnetwork.DataTextField = "netw_name";
        this.ddlnetwork.DataSource = dt2;
        this.ddlnetwork.DataBind();
        KeepStyle();
    }
    protected void ddlMachineid_SelectedIndexChanged(object sender, EventArgs e)
    {
        string sddlMachine = ddlMachineid.SelectedValue.ToString().Trim();
        DataTable dt2 = MyNt.GetNetWorks ("a.mroom_id = '" + sddlMachine + "'");
        this.ddlnetwork.DataValueField = "netw_id";
        this.ddlnetwork.DataTextField = "netw_name";
        this.ddlnetwork.DataSource = dt2;
        this.ddlnetwork.DataBind();
        KeepStyle();
    }

    /// <summary>
    /// 保存相应的状态
    /// </summary>
    protected void KeepStyle()
    {
        if (ChoiceDt.Checked == true)
        {
            ifChoiceDt.Style.Add("display", "");
            AllDt.Style.Add("display", "none");
            LDt.Value = "";
        }
        else
        {
            ifChoiceDt.Style.Add("display", "none");
            AllDt.Style.Add("display", "");
            LDt.Value = "全部日期";
        }
    }

    /// <summary>
    /// 全选
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtnAll_Click(object sender, EventArgs e)
    {
        HtmlInputCheckBox chk;
        string sTemp = "";
        if (hidAll.Value == "1")
        {
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                chk = (HtmlInputCheckBox)(GridView1.Rows[i].Cells[0].FindControl("OneCheck"));
                chk.Checked = true;
                sTemp += chk.Value + "|";
            }
            ChoiceInfo.Value = ChoiceInfo.Value + sTemp;
        }
        else
        {
            string sTempNo = "";
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                chk = (HtmlInputCheckBox)(GridView1.Rows[i].Cells[0].FindControl("OneCheck"));
                chk.Checked = false;
                sTempNo += chk.Value + "|";
            }
            ChoiceInfo.Value = ChoiceInfo.Value.Replace(sTempNo, "");
        }
    }

}